package com.kuanter.kuanterauto;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.ActivityGroup;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager.WakeLock;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.MKEvent;
import com.baidu.mapapi.MKGeneralListener;
import com.kuanter.adapter.HomeGroupAdapter;
import com.kuanter.kuanterauto.baseui.BaseActivityGroup;
import com.kuanter.kuanterauto.baseui.ProApplication;
import com.kuanter.kuanterauto.chexian.ChexianActivity;
import com.kuanter.kuanterauto.constants.MainConstants;
import com.kuanter.kuanterauto.dataservices.PushServices;
import com.kuanter.kuanterauto.entity.MapResult;
import com.kuanter.kuanterauto.entity.MessageInfo;
import com.kuanter.kuanterauto.entity.MessageInfoList;
import com.kuanter.kuanterauto.huiyuan.HuiYuanActivity;
import com.kuanter.kuanterauto.message.MessageListActivity;
import com.kuanter.kuanterauto.net.HttpTask;
import com.kuanter.kuanterauto.net.HttpUtil;
import com.kuanter.kuanterauto.param.ActivityHolder;
import com.kuanter.kuanterauto.setting.SettingActivity;
import com.kuanter.kuanterauto.userlogin.UserLoginActivity;
import com.kuanter.kuanterauto.utils.DataLoader;
import com.kuanter.kuanterauto.utils.DimensUtil;
import com.kuanter.kuanterauto.utils.StringUtils;
import com.kuanter.kuanterauto.website.WebSiteActivity;
import com.umeng.analytics.MobclickAgent;

/**
 * 主界面
 * 
 * @author soup
 * 
 */
@SuppressLint("HandlerLeak")
public class HomeActivityGroup extends BaseActivityGroup {

	public static BMapManager mBMapMan = null;

	public static GridView gvNavigationBar;
	public static HomeActivityGroup homeActivityGroup = null;
	public static HomeGroupAdapter adapter;

	public static LinearLayout layBody;// װ 装载sub Activity的容器

	private int width;
//	private int height;

	private static Window subActivity;
	MapResult mapR = null;

	public static int[] topbar_image_array = { R.drawable.wdpress,
			R.drawable.cxpress, R.drawable.hypress, R.drawable.xxpress,
			R.drawable.szpress };

	ProApplication application = (ProApplication) this.getApplication();

	public static String backAction = "";

//	Bundle carinfos_bundle = null;// 数据
	Bundle msgBundle=null;

	private DataReceiver dataReceiver = null;

	// int select_id=0;

	private List<Integer> select_id = null;// 记录点击子项的id容器

	// android:theme="@style/ContentOverlay"

	WakeLock wakeLock = null;

	long flag = -1;// 退出开关
	
	DisplayMetrics dm= null;
	
	DataLoader dataLoader=null;
	
	
	String versionInfo="";
	
	Handler handler=new Handler(){
		public void handleMessage(android.os.Message msg) {
			switch(msg.what){
			case HttpTask.RESULT_OK:
				Bundle bundle = msg.getData();
				String json = bundle.getString("result");
				System.out.println(json);
				MessageInfoList msgList=new MessageInfoList(json);
				List<MessageInfo> messageInfos=msgList.getMessageInfos();
				if(messageInfos!=null&&messageInfos.size()>0){
					adapter.showReaddian();
				}
				msgBundle=new Bundle();
				msgBundle.putSerializable(MessageInfo.TAG, (Serializable)messageInfos);
			case HttpTask.RESULT_ERROR:
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.home_group);
		mapR = MapResult.getMapResults();

		mBMapMan = new BMapManager(this);
		mBMapMan.init("755CDC09D6ACCAD8274A01D02576948F7904B7A1",
				new MyGeneralListener());
		select_id = new ArrayList<Integer>();
		dataLoader=new DataLoader(this);
		
//		carinfos_bundle = new Bundle();
		if (getIntent().getExtras() != null) {
//			carinfos_bundle.putSerializable(CardInfoList.TAG, getIntent()
//					.getSerializableExtra(CardInfoList.TAG));
//			carinfos_bundle.putSerializable(ConsumptionList.TAG, getIntent()
//					.getSerializableExtra(ConsumptionList.TAG));
//			carinfos_bundle.putSerializable(VehicleInfoList.TAG, getIntent()
//					.getSerializableExtra(VehicleInfoList.TAG));
			msgBundle=getIntent().getExtras();
		}else{
			System.out.println("msg_home");
			List<NameValuePair> params=new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("deviceToken", MainActivity.Token));
			dataLoader.DisplayData(MainConstants.HOST+"query_unRead_message", params, handler, "", false);
		}

		
		
		

		register_Receiver();

		initVariable();
		initView();
		initListener();
		bindData();
		getData(ProApplication.KUANTER_WD);// 默认打开第0页
		
//		getVersion();
//		checkVersion();
	}

	@Override
	protected void onResume() {
		MobclickAgent.onResume(this);
		super.onResume();
	}

	@Override
	protected void onPause() {
		MobclickAgent.onPause(this);
		super.onPause();
	}

	@Override
	protected void onStop() {
		super.onStop();
	}

	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();
		System.out.println(backAction);
		if (!backAction.equals("")) {
			if (backAction.equals(MainConstants.CX_ACTION)) {
				getData(ProApplication.KUANTER_CX);
			} else if (backAction.equals(MainConstants.HY_ACTION)) {
				getData(ProApplication.KUANTER_HY);
			} else if (backAction.equals(MainConstants.BACK_ACTION)) {
				getData(select_id.get(select_id.size() - 2));
				select_id.remove(select_id.size() - 2);
			} else if (backAction.equals(MainConstants.SZ_ACTION)) {
				getData(ProApplication.KUANTER_SZ);
			}
		} else {
			getData(ProApplication.KUANTER_WD);// 默认打开第0页
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (dataReceiver != null) {
			unregisterReceiver(dataReceiver);
			dataReceiver = null;
		}

		if (select_id != null) {
			select_id.clear();
			select_id = null;
		}

		if (mBMapMan != null) {
			mBMapMan.destroy();
			mBMapMan = null;
		}

		mapR.clearCache();

		MainActivity.ID = 0;

	}

	private void initVariable() {
		width = this.getWindowManager().getDefaultDisplay().getWidth()
				/ topbar_image_array.length;
//		height = this.getWindowManager().getDefaultDisplay().getHeight();

		homeActivityGroup = this;
	}

	private void initView() {
		layBody = (LinearLayout) findViewById(R.id.layBody);
		gvNavigationBar = (GridView) this.findViewById(R.id.gvNavigationBar); // //
																				// 底部bar
		gvNavigationBar.setNumColumns(topbar_image_array.length);// 设置每行列数
		gvNavigationBar.setGravity(Gravity.BOTTOM);// 位置居中
		gvNavigationBar.setVerticalSpacing(0);// 垂直间隔
	}

	private void bindData() {
		// adapter = new HomeGroupAdapter(this, topbar_image_array, width,
		// DimensUtil.dipTopx(this, 56));
		
//       480X800
        
		dm= new DisplayMetrics();
	    getWindowManager().getDefaultDisplay().getMetrics(dm);
	    String strOpt=dm.widthPixels+"X"+dm.heightPixels;
	    System.out.println(strOpt);

	    if(strOpt.equals("480X800")){
	    	adapter = new HomeGroupAdapter(this, topbar_image_array, width,
					DimensUtil.dipTopx(this, 52));
	    }else if(strOpt.equals("720X1280")){
	    	adapter = new HomeGroupAdapter(this, topbar_image_array, width,
					DimensUtil.dipTopx(this, 55));
	    }else if(strOpt.equals("800X1280")){
	    	adapter = new HomeGroupAdapter(this, topbar_image_array, width,
					DimensUtil.dipTopx(this, 57));
	    }else if(strOpt.equals("480X854")){
	    	adapter = new HomeGroupAdapter(this, topbar_image_array, width,
					DimensUtil.dipTopx(this, 52));
	    }else if(strOpt.equals("540X960")){
	    	adapter = new HomeGroupAdapter(this, topbar_image_array, width,
					DimensUtil.dipTopx(this, 55));
	    }else{
	    	adapter = new HomeGroupAdapter(this, topbar_image_array, width,
					DimensUtil.dipTopx(this, 52));
	    }
	    
//		switch (height) {
//		case 1280:
//			adapter = new HomeGroupAdapter(this, topbar_image_array, width,
//					DimensUtil.dipTopx(this, 55));
//			break;
//		case 960:
//			adapter = new HomeGroupAdapter(this, topbar_image_array, width,
//					DimensUtil.dipTopx(this, 55));
//			break;
//		case 854:
//			adapter = new HomeGroupAdapter(this, topbar_image_array, width,
//					DimensUtil.dipTopx(this, 52));
//			break;
//		case 800:
//			adapter = new HomeGroupAdapter(this, topbar_image_array, width,
//					DimensUtil.dipTopx(this, 52));
//			break;
//		default:
//			adapter = new HomeGroupAdapter(this, topbar_image_array, width,
//					DimensUtil.dipTopx(this, 52));
//			break;
//		}
		
		if (MainActivity.isPush) {
			adapter.showReaddian();
		}

		gvNavigationBar.setAdapter(adapter);// 设置菜单Adapter
	}

	public void initListener() {
		// 项目点击事件
		gvNavigationBar.setOnItemClickListener(new gridClickListener());
	}

	class gridClickListener implements OnItemClickListener {
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			getData(arg2);
		}
	}

	/**
	 * 根据ID加载指定的Activity 数据
	 * 
	 * @param id
	 *            GridView选中项的序号
	 */
	private void getData(int index) {
		switch (index) {
		case ProApplication.KUANTER_WD:// 网点
			switchActivity(ProApplication.KUANTER_WD);
			break;
		case ProApplication.KUANTER_CX:// 车险
			switchActivity(ProApplication.KUANTER_CX);
			break;
		case ProApplication.KUANTER_HY:// 会员
			switchActivity(ProApplication.KUANTER_HY);
			break;
		case ProApplication.KUANTER_XX:// 消息
			switchActivity(ProApplication.KUANTER_XX);
			break;
		case ProApplication.KUANTER_SZ:// 设置
			switchActivity(ProApplication.KUANTER_SZ);
			break;
		}
	}

	/**
	 * 根据ID打开指定的Activity
	 * 
	 * @param id
	 *            GridView选中项的序号
	 */
	private void switchActivity(int id) {
		// System.gc();
		adapter.setFocus(id);

		select_id.add(id);
		switch (id) {
		case ProApplication.KUANTER_WD:// 网点
			backAction = MainConstants.WD_ACTION;
			myStartActivity(WebSiteActivity.class, null);
			break;
		case ProApplication.KUANTER_CX:// 车险
			backAction = MainConstants.CX_ACTION;
			System.out.println(MainActivity.ID);
			if (MainActivity.ID == 0) {
				qStartActivity(UserLoginActivity.class, null,
						MainConstants.CX_ACTION);
				startActivity_anim(7);
			} else {
//				if (carinfos_bundle != null) {
//					myStartActivity(ChexianActivity.class, carinfos_bundle);
//				} else {
					myStartActivity(ChexianActivity.class, null);
//				}
			}
			break;
		case ProApplication.KUANTER_HY:// 会员
			System.out.println(MainActivity.ID);
			backAction = MainConstants.HY_ACTION;
			if (MainActivity.ID == 0) {
				qStartActivity(UserLoginActivity.class, null,
						MainConstants.HY_ACTION);
				startActivity_anim(7);
			} else {
//				if (carinfos_bundle != null) {
//					myStartActivity(HuiYuanActivity.class, carinfos_bundle);
//				} else {
					myStartActivity(HuiYuanActivity.class, null);
//				}
			}
			break;
		case ProApplication.KUANTER_XX:// 消息
			backAction = MainConstants.XX_ACTION;
			if(msgBundle!=null){
				System.out.println("not null");
				myStartActivity(MessageListActivity.class, msgBundle);
			}else{
				System.out.println("null");
			    myStartActivity(MessageListActivity.class, null);
			}
			adapter.goneReaddian();
			SharedPreferences sp = getSharedPreferences("push", MODE_PRIVATE);
			SharedPreferences.Editor editor = sp.edit();
			editor.putBoolean("push", false);
			editor.commit();
			break;
		case ProApplication.KUANTER_SZ:// 设置
			backAction = MainConstants.SZ_ACTION;
			myStartActivity(SettingActivity.class, null);
			break;
		}
	}

	/**
	 * 自定义跳转，可传参数
	 * 
	 * @param act
	 * @param bundle
	 */
	public static void myStartActivity(Class act, Bundle bundle) {
		Intent intent = null;
		layBody.removeAllViews();
		ActivityGroup ag = HomeActivityGroup.homeActivityGroup;
		intent = new Intent(ag, act);

		// if(!action.equals(""))
		// intent.setAction(action);

		ActivityHolder holder = new ActivityHolder();
		holder.setActClass(act);
		if (bundle != null) {

			holder.setBundle(bundle);
		}
		ProApplication.actStack.push(holder);
		if (bundle != null) {
			intent.putExtras(bundle);
		}
		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		// Activity 转为 View
		subActivity = ag.getLocalActivityManager().startActivity("subActivity",
				intent);
		// 容器添加View
		layBody.addView(subActivity.getDecorView(), LayoutParams.FILL_PARENT,
				LayoutParams.FILL_PARENT);
	}

	@Override
	public void onClick(View v) {

	}
	

	// <uses-permission
	// android:name="android.permission.DISABLE_KEYGUARD"></uses-permission>
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
			ExitApp();
			break;
		}
		return true;
	}

	public void ExitApp() {
		if (flag == -1 || System.currentTimeMillis() - flag > 2000) {
			showToast("再点击一次退出");
			flag = System.currentTimeMillis();

		} else if (System.currentTimeMillis() - flag < 2000) {
			startServices();
			finish();
		}
		
	}
	
	private void startServices(){
		Intent i = new Intent(this, PushServices.class);
		startService(i);
	}

	// @Override
	// public void onAttachedToWindow() {
	// this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
	// super.onAttachedToWindow();
	// }

	/**
	 * 注册广播
	 */
	private void register_Receiver() {
		IntentFilter filter = new IntentFilter();
		filter.addAction(MainConstants.Data_ACTION);
		dataReceiver = new DataReceiver();
		registerReceiver(dataReceiver, filter);
	}

	class DataReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent.getAction().equals(MainConstants.Data_ACTION)) {
				if (!backAction.equals("")) {
					System.out.println(backAction);
					if (backAction.equals(MainConstants.CX_ACTION)) {// 打开车险
						// vehicleinfos_bundle=null;
						// carinfos_bundle = null;
						// carinfos_bundle = intent.getExtras();
						getData(ProApplication.KUANTER_CX);
					} else if (backAction.equals(MainConstants.HY_ACTION)) {// 打开会员
						// carinfos_bundle = null;
						// carinfos_bundle = intent.getExtras();
						// carinfos = (List<CardInfo>)
						// bundle.getSerializable(CardInfoList.TAG);
						getData(ProApplication.KUANTER_HY);
					} else if (backAction.equals(MainConstants.SZ_ACTION)) {// 打开设置
						// carinfos_bundle = null;
						// carinfos_bundle = intent.getExtras();
						getData(ProApplication.KUANTER_SZ);
					} else if (backAction.equals(intent
							.getStringExtra("action"))) {// 默认打开第0页
						getData(ProApplication.KUANTER_WD);
					}
				} else {
					getData(ProApplication.KUANTER_WD);// 默认打开第0页
				}
			}
		}

	}

}

// 常用事件监听，用来处理通常的网络错误，授权验证错误等
class MyGeneralListener implements MKGeneralListener {

	@Override
	public void onGetNetworkState(int iError) {
		if (iError == MKEvent.ERROR_NETWORK_CONNECT) {
			System.out.println("您的网络出错啦！");
		} else if (iError == MKEvent.ERROR_NETWORK_DATA) {
			// Toast.makeText(DemoApplication.getInstance().getApplicationContext(),
			// "输入正确的检索条件！",
			// Toast.LENGTH_LONG).show();
			System.out.println("您的网络出错啦！");
		}
		// ...
	}

	@Override
	public void onGetPermissionState(int iError) {
		if (iError == MKEvent.ERROR_PERMISSION_DENIED) {
			// 授权Key错误：
			// Toast.makeText(DemoApplication.getInstance().getApplicationContext(),
			// "请在 DemoApplication.java文件输入正确的授权Key！",
			// Toast.LENGTH_LONG).show();
			// DemoApplication.getInstance().m_bKeyRight = false;
			System.out.println("授权Key错误：");
		}
	}
}
